package com.xiaoma.chat.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dexcoder.assistant.persistence.Criteria;
import com.dexcoder.assistant.persistence.JdbcDao;
import com.xiaoma.chat.domain.HistoryMessageRecord;
import com.xiaoma.chat.domain.SyncMessageRecord;
import com.xiaoma.chat.dto.HistoryMessageDto;
import com.xiaoma.chat.vo.MessageRecordVo;

@Service
public class HistoryService {

    @Autowired
    private JdbcDao jdbcDao;
    
    public void save(SyncMessageRecord syncMessageRecord) {
        jdbcDao.save(syncMessageRecord);
    }
    
    public SyncMessageRecord getLastRecord() {
        Criteria criteria = Criteria.create(SyncMessageRecord.class).desc("id");
        return jdbcDao.querySingleResult(criteria);
    }
    
    public void save(HistoryMessageRecord historyMessageRecord) {
        jdbcDao.save(historyMessageRecord);
    }
    
    public List<MessageRecordVo> findMessages(HistoryMessageDto dto) {
        Criteria criteria = Criteria.create(HistoryMessageRecord.class).where("dateTime", "like", new Object[]{"%" + dto.getDate() + "%"});
        if (StringUtils.isNotEmpty(dto.getFromUserId())) {
            criteria = criteria.and("fromUserId", new Object[]{dto.getFromUserId()});
        }
        if (StringUtils.isNotEmpty(dto.getTargetId())) {
            criteria = criteria.and("targetId", new Object[]{dto.getTargetId()});
        }
        if (StringUtils.isNotEmpty(dto.getGroupId())) {
            criteria = criteria.and("groupId", new Object[]{dto.getGroupId()});
        }
        if (null != dto.getTargetType()) {
            criteria = criteria.and("targetType", new Object[]{dto.getTargetType()});
        }
        List<HistoryMessageRecord> records = jdbcDao.queryList(criteria);
        List<MessageRecordVo> recordVos = new ArrayList<MessageRecordVo>(records.size());
        for (HistoryMessageRecord messageRecord: records) {
            recordVos.add(messageRecord.build());
        }
        return recordVos;
    }
}
